#include "WebClient.h"
WebClient::WebClient(GlobalConfig& config) : config(config), lastLoopTime(0)  {}

void WebClient::init() {
    // 可以在这里进行一些初始化操作，例如连接到服务器等
    // 目前暂不做具体操作
    debugLog("WebClient initialized.\n");
}

void WebClient::loop() {
    if (GlobalConstants::wifiConnected) {
//     实现定时发送 HTTP 请求
//     这里简单示例，后续可根据需求使用定时器
    unsigned long currentTime = millis();
        if (currentTime - lastLoopTime >= loopInterval) {
            sendRequest();
            lastLoopTime = currentTime;
        }
    }
}
// 上报请求
void WebClient::sendRequest() {
    if (WiFi.status() != WL_CONNECTED) {
        debugLog("WiFi is not connected. Cannot send HTTP request.\n");
        return;
    }

    WiFiClient wifiClient; // 创建一个 WiFiClient 对象
    HTTPClient httpClient; // 使用更具描述性的名称

    const std::string apiUrl = config.getHttpApiUrl();
    // 尝试初始化 HTTP 客户端
    if (!httpClient.begin(wifiClient, apiUrl.c_str())) {
        debugLog("Failed to initialize HTTP client for URL: %s\n", apiUrl.c_str());
        return;
    }

    const std::string apiType = config.getHttpApiType();
    int httpCode = 0;

//    if (apiType == "GET") {
        httpCode = httpClient.GET();
//    } else if (apiType == "POST") {
//        // 这里可添加 POST 请求的处理逻辑
//        // 假设存在一个获取 POST 数据的函数 getPostPayload()
//         String payload = getPostPayload();
//         httpCode = httpClient.POST(payload);
//        debugLog("POST request type is not fully implemented yet.\n");
//    } else {
//        debugLog("Unsupported HTTP request type: %s\n", apiType.c_str());
//        httpClient.end();
//        return;
//    }

    if (httpCode > 0) {
        debugLog("HTTP request sent, code: %d\n", httpCode);
        if (httpCode == HTTP_CODE_OK) {
            String responsePayload = httpClient.getString();
            debugLog("HTTP response payload: %s\n", responsePayload.c_str());
        }
    } else {
        debugLog("HTTP request failed, error: %s\n", httpClient.errorToString(httpCode).c_str());
    }

    httpClient.end();
}    